#include "Engine.h"

#include "Sphere.h"

#include <cstdlib>
#include <limits>
#include <memory.h>
#include <ctime>

using namespace RayTracer;

CEngine::CEngine(const CVector3& cameraPosition, const CVector4& background, int MaxTraceDepth, int waitTimer)
: m_CameraPosition(cameraPosition), m_Background(background), m_MaxTraceDepth(MaxTraceDepth)
{
	m_Scene = new Scene();
}

CEngine::~CEngine(void)
{
	delete m_Scene;
	if (m_LastRow)
		delete[] m_LastRow;
	if (m_Pixels)
		delete[] m_Pixels;
}

void CEngine::setTarget(int width, int height)
{
	// Set pixel buffer address and size
	m_Pixels = new float[width * height * 4];
	m_Width = width;
	m_Height = height;
}

CPrimitive* CEngine::RayTrace(CRay& ray, CVector4& acc, int traceDepth, float& rayDist)
{
	// TODO
}

void CEngine::InitRender()
{
	// Set first scanline to draw
	m_CurLine = 0;
	// Set first pixel buffer address
	m_PPos = 0;

	// TODO: Update (hard coded) Screen plane in world space coordinates
	m_WinX1 = -4;
	m_WinX2 = 4;
	m_WinY1 = m_SY = 3;
	m_WinY2 = -3;

	// Compute deltas
	m_DX = (m_WinX2 - m_WinX1) / m_Width;
	m_DY = (m_WinY2 - m_WinY1) / m_Height;

	// Allocate space for previous lines' primitives
	m_LastRow = new CPrimitive*[m_Width];
	memset(m_LastRow, NULL, m_Width * 4);		// 4 bytes for 32-bit addressing.
}

bool CEngine::Render()
{
	// Initialize the timer, clock tick: since program execution
	clock_t startClock = clock();

	// TODO

		// Check the timing and update the scene
		if (((clock() - startClock) * CLOCKS_PER_SEC / 1000) > m_WaitTimer)
		{
			// Return control to windows to update the screen
			m_CurLine = y + 1;
			return false;
		}
	}
	// all done
	return true;
}
